import { NextRequest, NextResponse } from 'next/server';
import { PrismaClient } from '@prisma/client';

const prisma = new PrismaClient();

export async function GET(request: NextRequest) {
  try {
    const url = new URL(request.url || 'http://localhost');
    const tokenId = url.searchParams.get('tokenId');

    if (!tokenId) {
      return NextResponse.json({ error: '缺少tokenId参数' }, { status: 400 });
    }

    // 设置最大查询范围为4小时
    const now = new Date();
    const maxStartTime = new Date();
    maxStartTime.setHours(now.getHours() - 4);

    // 首先尝试获取所有数据，如果数据太多则限制在4小时内
    let priceData = await prisma.priceData.findMany({
      where: {
        tokenId: tokenId
      },
      orderBy: {
        timestamp: 'desc'
      },
      take: 300, // 最多取300条记录（约5小时的数据）
      select: {
        timestamp: true,
        price: true,
        rsi: true
      }
    });

    // 如果数据超过4小时，则只保留4小时内的数据
    if (priceData.length > 0) {
      priceData = priceData.filter(record => record.timestamp >= maxStartTime);
    }

    // 按时间正序排列
    priceData = priceData.reverse();

    console.log(`RSI API调试: tokenId=${tokenId}, 最大查询时间=${maxStartTime.toISOString()}, 找到数据条数=${priceData.length}`);

    // 如果数据库中没有RSI值，需要实时计算
    const rsiHistory = [];
    
    for (let i = 0; i < priceData.length; i++) {
      const record = priceData[i];
      let rsiValue = record.rsi;

      // 如果数据库中没有RSI值，基于历史数据计算
      if (rsiValue === null && i >= 14) {
        const recentPrices = priceData.slice(Math.max(0, i - 14), i + 1).map(r => r.price);
        rsiValue = calculateRSI(recentPrices);
      }

      rsiHistory.push({
        timestamp: record.timestamp.toISOString(),
        price: record.price,
        rsi: rsiValue || 50 // 默认中性值
      });
    }

    return NextResponse.json(rsiHistory);

  } catch (error) {
    console.error('获取RSI历史数据失败:', error);
    return NextResponse.json(
      { error: '获取RSI历史数据失败' },
      { status: 500 }
    );
  }
}

// RSI计算函数
function calculateRSI(prices: number[], period: number = 14): number {
  if (prices.length < period + 1) {
    return 50; // 数据不足时返回中性值
  }

  const gains: number[] = [];
  const losses: number[] = [];

  // 计算价格变化
  for (let i = 1; i < prices.length; i++) {
    const change = prices[i] - prices[i - 1];
    gains.push(change > 0 ? change : 0);
    losses.push(change < 0 ? Math.abs(change) : 0);
  }

  // 计算平均收益和损失
  const avgGain = gains.slice(-period).reduce((sum, gain) => sum + gain, 0) / period;
  const avgLoss = losses.slice(-period).reduce((sum, loss) => sum + loss, 0) / period;

  // 处理边界情况
  if (avgGain === 0 && avgLoss === 0) {
    return 50;
  }

  if (avgLoss === 0) {
    return 100;
  }

  const rs = avgGain / avgLoss;
  const rsi = 100 - (100 / (1 + rs));

  return Math.round(rsi * 100) / 100;
}
